This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 0.1.2
Category: Required
Analysis Type: Decidable,Single Translation Unit
Amplification
This rule only applies when the function is called explicitly using function call syntax.
Rationale
It is possible to call a function without using [1] the return value, which may be an error. If the return value of a function is intended
to be explicitly discarded, it should be cast to void
to ensure that it is used [1].
Overloaded operators are excluded from this requirement, as they should behave in the same way as built-in operators.
Note: this rule effectively requires all non-void
functions to be treated as if they were declared
[[nodiscard]]
.
Example
uint16_t func();
void discarded()
{
func(); // Non-compliant - implicitly discarded
( void )func(); // Compliant - void cast is a use
auto b = func(); // Compliant - used as initializer
}
void f1( std::string q )
{
std::string s { q } ; // Rule does not apply - not function call syntax
s = q; // Rule does not apply - not function call syntax
s.operator=( q ); // Non-compliant
}
void f2( std::function< int() > & f )
{
f(); // Non-compliant - using function call syntax
auto a = []() { return 10; };
a(); // Non-compliant - using function call syntax
}
Glossary
[1] Use / used / using
An object is used if:
- It is the subject of a cast; or
- It is explicitly initialized at declaration time; or
- It is an operand in an expression; or
- It is referenced.
A function is used as defined in M23_331: MISRA C++ 2023 Rule 0.2.4.
A type is used as defined in MISRA C++ 2023 Rule 0.2.3 (Types with limited visibility should be used at least
once).
Copyright The MISRA Consortium Limited © 2023